/**
 * 
 */
package org.pump.client.main;

import java.nio.ByteOrder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.pump.client.codec.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 *
 */
public class MysqlEncoder extends ProtocolEncoderAdapter{
	private static final Logger mylog = LoggerFactory
			.getLogger(MysqlEncoder.class);
	static IoBuffer buf = IoBuffer.allocate(1024, false);
	static {
		buf.setAutoExpand(true);
		buf.order(ByteOrder.LITTLE_ENDIAN);
	}
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		Packet msgPack = (Packet)message;
		
		buf.sweep();
		if(!msgPack.getHead().writebuffer(buf))
		{
			mylog.error("write head fail");
		}
		
		if(!msgPack.getBody().writebuffer(buf))
		{
			mylog.error("write body fail");
		}
		
		buf.flip();
		out.write(buf);

		if (mylog.isDebugEnabled()) {
			mylog.debug("successfully encode " + buf);
		}
	}
}
